package vtc;

import java.util.concurrent.*;
import com.tictactec.ta.lib.*;
import java.util.*;


abstract public class VectorialFunctionalUnit extends VtcUnit
{
	static Core talib_;
	Integer n_;
	Date oldDate_;
	double[] data_;
	double output_;
	
	VectorialFunctionalUnit(String id, VtcArrayBlockingQueue inQueues[], VtcArrayBlockingQueue outQueues[], Integer n)
	{
		super(id, inQueues, outQueues);
		n_ = n;
		oldDate_ = new Date(); 
		if(talib_ == null)
			talib_ = new Core();
	}
	
	abstract public void functionalProcess() throws InterruptedException;
	
	public void process() throws InterruptedException
	{
		VtcTimeTaggedEvent[] events = inQueues_[0].getOldestEvents(n_, false);
		if(events.length == n_)
		{
			Date timeTag = events[n_-1].getTimeTag();
			if(oldDate_ == timeTag)
			{
				//do nothing when last iteration data == new iteration data and wait a little bit
				try
				{
					TimeUnit.MILLISECONDS.sleep(50);
				}
				catch(InterruptedException e)
				{
					System.out.print("Interrupted while sleeping in EMA::process()\n");
					throw e;
				}
			}
			else
			{
				this.data_ = new double[n_];
				for(int i = 0; i < n_; i++)
				{
					data_[i] = (Double) events[i].getEvent();
				}
				//This function just generates 1 value (output) f(data1,...,datan)=output
				this.functionalProcess();
				VtcTimeTaggedEvent event = new VtcTimeTaggedEvent(output_, timeTag);
				outQueues_[0].forcePut(event);
			}
			oldDate_ = timeTag;
		}
	}
}